package com.example.orderservice.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sentinel/")
@Slf4j
public class SentinelController {

    private static final String RESOURCE = "sentinel-source";


    @PostMapping("test")
    public String test(){
        Entry entry = null;
        try {
            entry = SphU.entry(RESOURCE);
            //资源
            String str = "业务逻辑";
            log.info("============"+ str + "============");
            return str;
        } catch (BlockException e) {
            log.info("blocking.....");
            return "业务被限流";
        } catch (Exception e){
            Tracer.traceEntry(e, entry);
        } finally {
            if (entry != null){
                entry.exit();
            }
        }
        return null;
    }

    @PostConstruct
    private static void initFlowRule(){
        List<FlowRule> list = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource(RESOURCE);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        list.add(rule);
        FlowRuleManager.loadRules(list);
    }


}
